package com.sfx.concurrent.demo.concurrent.visibility;

import lombok.extern.slf4j.Slf4j;

/**
 * Balking模式->犹豫模式
 */
@Slf4j(topic = "c.interruptTestDemo")
public class Balking {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination1 tpt = new TwoPhaseTermination1();
        tpt.start();
        tpt.start();
        tpt.start();
        tpt.start();

    }
}
//两阶段终止模式
@Slf4j(topic = "c.TwoPhaseTermination")
class TwoPhaseTermination1{
    private Thread monitor;//监控线程
    private volatile boolean stop = false;
    //是否调用了start方法
    private boolean starting = false;
    //启动线程
    public void start(){
        synchronized (this) {
            if(starting){
                return;
            }
            starting = true;
        }
        //监控线程
        monitor = new Thread(()->{
            while(true){
                //获取打断标记
                Thread current = Thread.currentThread();//执行监控记录的线程
                if(stop){//不会清除打断标记  interrupted静态方法会清楚打断标记
                    //如果被打断,料理完后事,就退出循环
                    log.debug("料理完后事,就退出循环!!!");
                    break;
                }
                //没有被打断,就睡眠1s之后,进行监控记录
                try {
                    Thread.sleep(1000);//可能被打断->触发异常进入catch块
                    log.debug("current : 执行监控记录");//可能被打断->打断标记为true下次不进入循环
                } catch (InterruptedException e) {
                }
            }
        },"monitor");
        //启动监控线程
        monitor.start();
    }
    //终止线程
    public void stop(){
        stop = true;
        monitor.interrupt();//设置打断标记
    }
    //mvn archetype:generate -DinteractiveMode=false -DarchetypeGroupId=org.openjdk.jcstress -
    //DarchetypeArtifactId=jcstress-java-test-archetype -DarchetypeVersion=0.5 -DgroupId=cn.itcast -
    //DartifactId=ordering -Dversion=1.0
}